/*
 * Copyright (c) 2011, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "Win32EventDriver.h"

namespace alkes {

#define INTERVAL_TIMER_ID 1

const static struct {
    const char* libname;
    const char* symname;
} s_sym_table[] = {
    {NULL, NULL},   // AL_DEVICE_TYPE_NONE
    {"alkes-opengl.dll", "alkes_create_graphics"},      // AL_DEVICE_TYPE_OPENGL
    {"alkes-opengl.dll", "alkes_create_graphics_shader"},// AL_DEVICE_TYPE_OPENGL_SHADER
    {"alkes-opengl.dll", "alkes_create_graphics_noshader"},// AL_DEVICE_TYPE_OPENGL_NOSHADER
    {"alkes-opengl.dll", "alkes_create_graphics_noshader"},// AL_DEVICE_TYPE_OPENGL_ES1
    {"alkes-gles2.dll", "alkes_create_graphics"},       // AL_DEVICE_TYPE_OPENGL_ES2
    {"alkes-directx9.dll", "alkes_create_graphics"},    // AL_DEVICE_TYPE_DIRECTX9
};

Win32EventDriver::Win32EventDriver()
: device_(0)
{
}

Win32EventDriver::~Win32EventDriver()
{
}

NativeWindow Win32EventDriver::getNativeWindow() const
{
    return window_.getHWND();
}

IGraphicsDevice* Win32EventDriver::createDevice(IApplication* app)
{
    uint16_t w = app->getWidth();
    uint16_t h = app->getHeight();
    const char* title = app->getTitle();

    if (!window_.initialize(w, h, title))
        return 0;

    IGraphicsDevice* device = 0;
    GraphicsDeviceFactory factory = app->getDeviceFactory();
    if (factory)
    {
        device = factory(app->getDeviceType(), window_.getHWND());
    }
    else
    {
        DeviceType type = app->getDeviceType();
        if (0 < type && type < AL_LENGTH(s_sym_table))
        {
            shared_ = new SharedLibrary(s_sym_table[type].libname);
            IGraphicsDevice* (*symbol)(void*, uint16_t, uint16_t) =
                (IGraphicsDevice* (*)(void*, uint16_t, uint16_t))shared_->getFunction(s_sym_table[type].symname);
            if (symbol)
            {
                device = symbol(window_.getHWND(), w, h);
            }
        }
    }

    device_ = device;

    return device;
}

void Win32EventDriver::destroyDevice(IGraphicsDevice* /*device*/)
{
    device_ = 0;
    if (shared_)
    {
        delete shared_;
        shared_ = 0;
    }
    window_.finalize();
}

int Win32EventDriver::mainloop(IApplication* app)
{
    window_.show(Win32Window::AL_WINDOW_SHOW);

    HWND hwnd = window_.getHWND();

    BOOL ret;
    MSG msg;

    SetTimer(hwnd, INTERVAL_TIMER_ID, 10, NULL);

    while (0 < (ret = ::GetMessage(&msg, hwnd, 0, 0)))
    {
        switch (msg.message)
        {
        case WM_PAINT:
            {
                RECT window_rect;
                if (FALSE != ::GetUpdateRect(hwnd, &window_rect, FALSE))
                {
                    Rect rect;
                    rect.x = (Rect::value_type)window_rect.left;
                    rect.y = (Rect::value_type)window_rect.top;
                    rect.width = (Rect::value_type)(window_rect.right - window_rect.left);
                    rect.height = (Rect::value_type)(window_rect.bottom - window_rect.top);

                    app->invokeDirty(rect);
                }

                app->invokeDraw();
            }
            break;

        case WM_TIMER:
            if (msg.wParam == INTERVAL_TIMER_ID)
            {
                app->invokeDraw();
//                ::InvalidateRect(hwnd, NULL, FALSE);
            }
            break;

        case WM_MOUSEMOVE:
            app->invokeMouseMove(LOWORD(msg.lParam), HIWORD(msg.lParam));
            break;

        case WM_LBUTTONDOWN:
            app->invokePress(AL_VK_LBUTTON);
            break;
        case WM_LBUTTONUP:
            app->invokeRelease(AL_VK_LBUTTON);
            break;
        case WM_RBUTTONDOWN:
            app->invokePress(AL_VK_RBUTTON);
            break;
        case WM_RBUTTONUP:
            app->invokeRelease(AL_VK_RBUTTON);
            break;
        case WM_MBUTTONDOWN:
            app->invokePress(AL_VK_MBUTTON);
            break;
        case WM_MBUTTONUP:
            app->invokeRelease(AL_VK_MBUTTON);
            break;
        case WM_KEYDOWN:
            if (msg.wParam <= AL_VK_NUM)
            {
                app->invokePress((KeyEvent)msg.wParam);
            }
            break;
        case WM_KEYUP:
            if (msg.wParam <= AL_VK_NUM)
            {
                app->invokeRelease((KeyEvent)msg.wParam);
            }
            break;

        case WM_SIZE:
            app->invokeResize(LOWORD(msg.lParam), HIWORD(msg.lParam));
            break;

        case WM_ERASEBKGND:
            break;

        default:
            ::DefWindowProc(hwnd, msg.message, msg.wParam, msg.lParam);
            break;
        }
    }

    KillTimer(hwnd, INTERVAL_TIMER_ID);

    return 0;
}

}
